import { useState, useEffect } from 'react';
import { View, Text, ScrollView, ActivityIndicator, TouchableOpacity, RefreshControl, Alert, Modal, Image, Platform, Pressable, TextInput, FlatList, Linking } from 'react-native';
import { Stack, useLocalSearchParams, useRouter } from 'expo-router';
import { Ionicons, MaterialIcons } from '@expo/vector-icons';
import { Picker } from '@react-native-picker/picker';
import { Container } from '../../../components/Container';
import apiService from '../../../services/api';
import { API_BASE_URL } from '../../../constants/api';
import * as ImagePicker from 'expo-image-picker';
import * as DocumentPicker from 'expo-document-picker';
import { LinearGradient } from 'expo-linear-gradient';
import { useAuth } from '../../../utils/auth/authContext';
import { getToken } from '../../../utils/auth/tokenStorage';
import HandwrittenSignature from '../../../components/HandwrittenSignature';
import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';
import BatchReceiptUploader from '../../../components/BatchReceiptUploader';

// 主题详情数据接口
interface ThemeDetail {
  serialNo: string;
  title: string;
  description: string;
  amount: number;
  status: string;
  createTime: string;
  userId: string;
  creator_name?: string;
  receiptsCount: number;
  totalAmount: number;
  signature?: {
    signatureData: string;
    createdAt: string;
  } | null;
  participants: {
    userId: string;
    name: string;
    email: string;
    role: string;
  }[];
  receipts: {
    serialNo: string;
    amount: number;
    date: string;
    vendor: string;
    feeType?: string;
    category: string;
    buyer?: string;
    receiptType?: string;
    notes?: string;
    status: string;
    createTime?: string;
    uploaded_by_id?: string;
    uploaded_by_name: string;
    attachments: {
      serialNo: string;
      receiptSerialNo?: string;
      fileName: string;
      isReceipt: boolean;
      ocrProcessed?: boolean;
      ocrData?: string;
      storageName?: string;
      storageType?: string;
      remark?: string;
      fileType?: string;
      storageBucket?: string;
    }[];
  }[];
  oa?: string;
}

export default function ThemeDetailScreen() {
  const { id } = useLocalSearchParams();
  const router = useRouter();
  const auth = useAuth();
  const [theme, setTheme] = useState<ThemeDetail | null>(null);
  const [loading, setLoading] = useState(true);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [uploadModalVisible, setUploadModalVisible] = useState(false);
  const [uploading, setUploading] = useState(false);
  const [participantsExpanded, setParticipantsExpanded] = useState(false);
  
  // OA编码相关状态
  const [isEditingOa, setIsEditingOa] = useState(false);
  const [oaValue, setOaValue] = useState('');

  // 添加参与者管理相关状态
  const [showAddParticipantModal, setShowAddParticipantModal] = useState(false);
  const [showAddProxyModal, setShowAddProxyModal] = useState(false);
  const [showParticipantDeleteConfirm, setShowParticipantDeleteConfirm] = useState(false);
  const [participantToDelete, setParticipantToDelete] = useState<string | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [searchResults, setSearchResults] = useState<any[]>([]);
  const [selectedUsers, setSelectedUsers] = useState<any[]>([]);
  const [isSearching, setIsSearching] = useState(false);

  // 添加签名相关状态
  const [showSignatureModal, setShowSignatureModal] = useState(false);
  const [isGeneratingSignature, setIsGeneratingSignature] = useState(false);
  const [showSignature, setShowSignature] = useState(false);
  
  // 添加收据详情相关状态
  const [selectedReceipt, setSelectedReceipt] = useState<any>(null);
  const [showReceiptDetailModal, setShowReceiptDetailModal] = useState(false);
  const [showReceiptEditModal, setShowReceiptEditModal] = useState(false);
  const [showDeleteReceiptConfirm, setShowDeleteReceiptConfirm] = useState(false);
  const [receiptToDelete, setReceiptToDelete] = useState<string | null>(null);
  const [editedReceiptData, setEditedReceiptData] = useState<any>(null);
  const [showAttachmentActions, setShowAttachmentActions] = useState(false);
  const [attachments, setAttachments] = useState<any[]>([]);

  // 当前查看的附件
  const [viewingAttachment, setViewingAttachment] = useState<string | null>(null);
  const [showMultiUploadModal, setShowMultiUploadModal] = useState(false);

  const [showUploadOptions, setShowUploadOptions] = useState(false);
  const [selectedTab, setSelectedTab] = useState('single');

  // 在selectedReceipt变化时更新attachments
  useEffect(() => {
    if (selectedReceipt?.attachments) {
      setAttachments(selectedReceipt.attachments);
    } else {
      setAttachments([]);
    }
  }, [selectedReceipt]);

  // 加载主题详细数据
  const loadThemeDetail = async () => {
    if (!id) {
      setError('主题ID不能为空');
      setLoading(false);
      return;
    }
    
    setLoading(true);
    setError(null);
    
    try {
      const response = await apiService.themes.get(id as string);
      
      if (response.messageStatus === 'success' && response.data) {
        setTheme(response.data);
      } else {
        throw new Error(response.message || '获取主题详情失败');
      }
    } catch (err: any) {
      console.error('加载主题详情失败:', err);
      setError(err.message || '加载主题详情时发生错误');
      setTheme(null);
    } finally {
      setLoading(false);
      setRefreshing(false);
    }
  };

  // 初始加载
  useEffect(() => {
    loadThemeDetail();
  }, [id]);

  // 下拉刷新处理
  const handleRefresh = () => {
    setRefreshing(true);
    loadThemeDetail();
  };

  // 格式化金额显示
  const formatAmount = (amount: number | null | undefined) => {
    if (amount === null || amount === undefined) {
      return '¥0.00';
    }
    return typeof amount === 'number' && !isNaN(amount) ? `¥${amount.toFixed(2)}` : '¥0.00';
  };

  // 获取状态对应的颜色
  const getStatusColor = (status: string) => {
    switch (status) {
      case 'active':
        return '#3B82F6'; // blue - 进行中
      case 'closed':
        return '#10B981'; // green - 已完成
      default:
        return '#9CA3AF'; // gray
    }
  };

  // 格式化日期显示
  const formatDate = (dateString: string) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN');
  };

  // 获取角色名称
  const getRoleName = (role: string) => {
    switch (role) {
      case 'admin':
        return '管理员';
      case 'contributor':
        return '参与者';
      case 'proxy':
        return '代理人';
      default:
        return '参与者';
    }
  };

  // 从相册选择图片
  const pickImage = async () => {
    try {
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: false,
        quality: 0.8,
      });

      if (!result.canceled && result.assets.length > 0) {
        const asset = result.assets[0];
        setUploadModalVisible(false);
        setShowUploadOptions(false);
        await uploadReceipt(asset.uri, asset.fileName || `image_${new Date().getTime()}.jpg`);
      }
    } catch (error) {
      Alert.alert('错误', '选择图片失败');
      console.error(error);
    }
  };

  // 拍照
  const takePhoto = async () => {
    try {
      const { status } = await ImagePicker.requestCameraPermissionsAsync();
      
      if (status !== 'granted') {
        Alert.alert('权限错误', '需要相机权限才能拍照');
        return;
      }

      const result = await ImagePicker.launchCameraAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: false,
        quality: 0.8,
      });

      if (!result.canceled && result.assets.length > 0) {
        const asset = result.assets[0];
        setUploadModalVisible(false);
        setShowUploadOptions(false);
        await uploadReceipt(asset.uri, `camera_${new Date().getTime()}.jpg`);
      }
    } catch (error) {
      Alert.alert('错误', '拍照失败');
      console.error(error);
    }
  };

  // 选择文档
  const pickDocument = async () => {
    try {
      const result = await DocumentPicker.getDocumentAsync({
        type: ['image/*', 'application/pdf']
      });

      if (!result.canceled && result.assets.length > 0) {
        const file = result.assets[0];
        setUploadModalVisible(false);
        setShowUploadOptions(false);
        await uploadReceipt(file.uri, file.name);
      }
    } catch (error) {
      Alert.alert('错误', '选择文档失败');
      console.error(error);
    }
  };

  // 上传收据
  const uploadReceipt = async (uri: string, fileName: string) => {
    if (!theme) return;
    
    setUploading(true);
    
    try {
      const token = await getToken();
      if (!token) {
        throw new Error('认证失败：无法获取token');
      }
      
      const uploadUrl = `${API_BASE_URL}/api/themes/receipts/upload`;
      
      console.log('准备上传文件:', {
        uri,
        fileName,
        themeSerialNo: theme.serialNo,
        token: token
      });
      
      // 使用Expo的文件系统API上传
      const uploadResult = await FileSystem.uploadAsync(
        uploadUrl,
        uri,
        {
          httpMethod: 'POST',
          uploadType: FileSystem.FileSystemUploadType.MULTIPART,
          fieldName: 'file', // 文件字段名
          mimeType: uri.endsWith('.pdf') ? 'application/pdf' : uri.endsWith('.png') ? 'image/png' : 'image/jpeg',
          parameters: {
            'theme_serial_no': theme.serialNo,
            'remark': '从移动应用上传'
          },
          headers: {
            'Authorization': `Bearer ${token}`,
            'Accept': 'application/json'
          }
        }
      );
      
      console.log('上传响应状态:', uploadResult.status);
      
      // 解析响应
      const result = JSON.parse(uploadResult.body);
      console.log('上传响应:', result);
      
      if (result.messageStatus === 'success') {
        Alert.alert('成功', '收据上传成功');
        await loadThemeDetail();
      } else {
        throw new Error(result.message || '上传失败');
      }
    } catch (error: any) {
      console.error('上传收据失败:', error);
      Alert.alert('错误', `上传失败: ${error.message || '未知错误'}`);
    } finally {
      setUploading(false);
    }
  };

  // 获取用户列表
  const searchUsers = async (query: string) => {
    if (!query.trim()) {
      setSearchResults([]);
      return;
    }
    
    setIsSearching(true);
    try {
      const response = await apiService.users.search(query);
      if (response.data) {
        setSearchResults(response.data);
      }
    } catch (error) {
      console.error('搜索用户失败:', error);
      Alert.alert('错误', '搜索用户失败');
    } finally {
      setIsSearching(false);
    }
  };

  // 处理用户搜索输入变化
  const handleSearchChange = (text: string) => {
    setSearchQuery(text);
    if (text.length > 1) {
      searchUsers(text);
    } else {
      setSearchResults([]);
    }
  };

  // 选择用户
  const handleSelectUser = (user: any) => {
    if (!selectedUsers.some(u => u.userId === user.userId)) {
      setSelectedUsers([...selectedUsers, user]);
    }
    setSearchQuery('');
    setSearchResults([]);
  };

  // 移除选中的用户
  const handleRemoveUser = (userId: string) => {
    setSelectedUsers(selectedUsers.filter(user => user.userId !== userId));
  };

  // 添加参与者
  const handleAddParticipants = async () => {
    if (selectedUsers.length === 0) {
      Alert.alert('提示', '请选择至少一位参与者');
      return;
    }
    
    try {
      const themeId = id as string;
      
      // 为每个新参与者发起请求
      for (const participant of selectedUsers) {
        const token = await getToken();
        if (!token) {
          throw new Error('认证失败：无法获取token');
        }
        
        const response = await fetch(`${API_BASE_URL}/api/themes/participants/add`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            themeSerialNo: themeId,
            userId: participant.userId,
            role: 'contributor' // 默认为贡献者角色
          }),
        });
        
        const result = await response.json();
        if (!result.messageStatus || result.messageStatus !== 'success') {
          throw new Error('添加参与者失败');
        }
      }
      
      // 更新本地状态
      const updatedParticipants = [...(theme?.participants || [])];
      selectedUsers.forEach(user => {
        if (!updatedParticipants.some(p => p.userId === user.userId)) {
          updatedParticipants.push({
            userId: user.userId,
            name: user.name,
            email: user.email || '',
            role: 'contributor'
          });
        }
      });
      
      setTheme(prev => prev ? {...prev, participants: updatedParticipants} : null);
      
      Alert.alert('成功', '已添加参与者');
      setShowAddParticipantModal(false);
      setSelectedUsers([]);
    } catch (error) {
      console.error('添加参与者失败:', error);
      Alert.alert('错误', '添加参与者失败');
    }
  };

  // 添加代理人
  const handleAddProxies = async () => {
    if (selectedUsers.length === 0) {
      Alert.alert('提示', '请选择至少一位代理人');
      return;
    }
    
    try {
      const themeId = id as string;
      
      // 为每个新代理人发起请求
      for (const proxy of selectedUsers) {
        const token = await getToken();
        if (!token) {
          throw new Error('认证失败：无法获取token');
        }
        
        const response = await fetch(`${API_BASE_URL}/api/themes/participants/add`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          body: JSON.stringify({
            themeSerialNo: themeId,
            userId: proxy.userId,
            role: 'proxy' // 设置为代理人角色
          }),
        });
        
        const result = await response.json();
        if (!result.messageStatus || result.messageStatus !== 'success') {
          throw new Error('添加代理人失败');
        }
      }
      
      // 更新本地状态
      const updatedParticipants = [...(theme?.participants || [])];
      selectedUsers.forEach(user => {
        if (!updatedParticipants.some(p => p.userId === user.userId)) {
          updatedParticipants.push({
            userId: user.userId,
            name: user.name,
            email: user.email || '',
            role: 'proxy'
          });
        }
      });
      
      setTheme(prev => prev ? {...prev, participants: updatedParticipants} : null);
      
      Alert.alert('成功', '已添加代理人');
      setShowAddProxyModal(false);
      setSelectedUsers([]);
    } catch (error) {
      console.error('添加代理人失败:', error);
      Alert.alert('错误', '添加代理人失败');
    }
  };

  // 删除参与者
  const handleDeleteParticipant = async () => {
    if (!participantToDelete || !theme) return;
    
    try {
      const token = await getToken();
      if (!token) {
        throw new Error('认证失败：无法获取token');
      }
      
      const response = await fetch(`${API_BASE_URL}/api/themes/participants/remove`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          themeSerialNo: id,
          userId: participantToDelete
        }),
      });
      
      const result = await response.json();
      if (result.messageStatus === 'success') {
        // 更新本地状态
        const updatedParticipants = theme.participants.filter(
          p => p.userId !== participantToDelete
        );
        
        setTheme({...theme, participants: updatedParticipants});
        Alert.alert('成功', '已移除参与者');
      } else {
        throw new Error('移除参与者失败');
      }
    } catch (error) {
      console.error('移除参与者失败:', error);
      Alert.alert('错误', '移除参与者失败');
    } finally {
      setShowParticipantDeleteConfirm(false);
      setParticipantToDelete(null);
    }
  };

  // 签名相关功能
  // 生成签名图片
  const generateSignature = async () => {
    if (!theme || !auth?.user?.name) return;
    
    try {
      setIsGeneratingSignature(true);
      
      const token = await getToken();
      if (!token) {
        throw new Error('认证失败：无法获取token');
      }
      
      const response = await fetch(`${API_BASE_URL}/api/themes/signature/generate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          themeSerialNo: id,
          userName: auth.user.name
        }),
      });
      
      const result = await response.json();
      
      if (result.messageStatus === 'success' && result.data) {
        // 更新主题数据以包含新的签名
        const signatureData = result.data.signatureData;
        const createdAt = result.data.createdAt;
        
        setTheme(prevTheme => {
          if (!prevTheme) return null;
          return {
            ...prevTheme,
            signature: {
              signatureData,
              createdAt
            }
          };
        });
        
        Alert.alert('成功', '签名生成成功');
      } else {
        Alert.alert('错误', '签名生成失败');
      }
    } catch (error) {
      console.error('Error generating signature:', error);
      Alert.alert('错误', '签名生成失败');
    } finally {
      setIsGeneratingSignature(false);
      setShowSignatureModal(false);
    }
  };

  // 上传签名图片
  const uploadSignature = async (uri: string) => {
    if (!theme) return;
    
    try {
      // 准备FormData
      const formData = new FormData();
      const filename = uri.split('/').pop() || 'signature.jpg';
      const fileType = filename.split('.').pop()?.toLowerCase() || 'jpg';
      const fileTypeStr = fileType === 'png' ? 'image/png' : 'image/jpeg';
      
      console.log('准备上传签名:', {
        uri,
        filename,
        fileTypeStr,
        themeSerialNo: theme.serialNo
      });
      
      // 添加文件 - 确保格式正确
      const fileObj = {
        uri: Platform.OS === 'ios' ? uri.replace('file://', '') : uri,
        name: filename,
        type: fileTypeStr,
      } as any;
      
      formData.append('file', fileObj);
      formData.append('themeSerialNo', theme.serialNo);
      
      const token = await getToken();
      
      const response = await fetch(`${API_BASE_URL}/api/themes/signature/upload`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json',
          // 不要设置Content-Type
        },
        body: formData,
      });
      
      console.log('签名上传响应状态:', response.status, response.statusText);
      
      // 检查响应状态
      if (!response.ok) {
        const errorText = await response.text();
        console.error('服务器错误响应:', errorText);
        throw new Error(`服务器返回错误: ${response.status} ${response.statusText}`);
      }
      
      const result = await response.json();
      
      if (result.messageStatus === 'success' && result.data) {
        // 更新主题数据以包含新的签名
        const signatureData = result.data.signatureData;
        const createdAt = result.data.createdAt;
        
        setTheme(prevTheme => {
          if (!prevTheme) return null;
          return {
            ...prevTheme,
            signature: {
              signatureData,
              createdAt
            }
          };
        });
        
        Alert.alert('成功', '签名上传成功');
      } else {
        Alert.alert('错误', '签名上传失败');
      }
    } catch (error) {
      console.error('Error uploading signature:', error);
      Alert.alert('错误', '签名上传失败');
    } finally {
      setShowSignatureModal(false);
    }
  };

  // 从图库选择签名图片
  const pickSignatureImage = async () => {
    try {
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ImagePicker.MediaTypeOptions.Images,
        allowsEditing: false,
        aspect: [4, 1],
        quality: 0.8,
      });

      if (!result.canceled && result.assets.length > 0) {
        uploadSignature(result.assets[0].uri);
      }
    } catch (error) {
      console.error('选择图片失败:', error);
      Alert.alert('错误', '选择图片失败');
    }
  };

  // 添加手写签名状态
  const [showHandwrittenSignatureModal, setShowHandwrittenSignatureModal] = useState(false);
  const [handwrittenSignature, setHandwrittenSignature] = useState<string | null>(null);

  // 处理手写签名
  const handleHandwrittenSignature = () => {
    setShowSignatureModal(false);
    setShowHandwrittenSignatureModal(true);
  };

  // 保存手写签名
  const saveHandwrittenSignature = async (signatureUri: string) => {
    try {
      console.log('准备保存签名...');
      
      if (!theme || !signatureUri) {
        Alert.alert('错误', '签名数据无效');
        return;
      }
      console.log('签名数据:', signatureUri);
      
      // 显示加载提示
      Alert.alert('上传中', '正在上传签名，请稍候...');
      
      // 获取token
      const token = await getToken();
      
      // 这里我们直接调用现有的上传签名API，不再尝试解析或转换签名数据
      const response = await fetch(`${API_BASE_URL}/api/themes/signature/generate`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          themeSerialNo: theme.serialNo,
          signData: signatureUri
        }),
      });
      
      const result = await response.json();
      
      if (result.messageStatus === 'success' && result.data) {
        // 更新主题数据以包含新的签名
        const signatureData = result.data.signatureData;
        const createdAt = result.data.createdAt;
        
        setTheme(prevTheme => {
          if (!prevTheme) return null;
          return {
            ...prevTheme,
            signature: {
              signatureData,
              createdAt
            }
          };
        });
        
        Alert.alert('成功', '签名生成成功');
      } else {
        throw new Error(result.message || '签名生成失败');
      }
    } catch (error) {
      console.error('签名处理失败:', error);
      Alert.alert('错误', '签名处理失败，请重试');
    } finally {
      // 关闭手写模态框
      setShowHandwrittenSignatureModal(false);
    }
  };

  // 签名上传/生成模态框
  const renderSignatureModal = () => {
    return (
      <Modal
        visible={showSignatureModal}
        transparent
        animationType="slide"
        onRequestClose={() => setShowSignatureModal(false)}
      >
        <View className="flex-1 justify-end bg-black/50">
          <View className="bg-white rounded-t-3xl p-6">
            <View className="items-center mb-6">
              <View className="w-10 h-1 bg-gray-300 rounded-full mb-2" />
              <Text className="text-xl font-bold">签名管理</Text>
            </View>

            {isGeneratingSignature ? (
              <View className="items-center py-8">
                <ActivityIndicator size="large" color="#3B82F6" />
                <Text className="mt-4 text-gray-500">正在生成签名...</Text>
              </View>
            ) : (
              <View className="gap-4">

                <Pressable 
                  className="flex-row items-center p-4 bg-purple-50 rounded-xl"
                  onPress={handleHandwrittenSignature}
                >
                  <View className="w-10 h-10 bg-purple-100 rounded-full items-center justify-center">
                    <Ionicons name="create-outline" size={24} color="#8B5CF6" />
                  </View>
                  <View className="ml-3">
                    <Text className="text-lg font-semibold">手写签名</Text>
                    <Text className="text-gray-500">在屏幕上手写您的签名</Text>
                  </View>
                </Pressable>

                <Pressable 
                  className="flex-row items-center p-4 bg-green-50 rounded-xl"
                  onPress={generateSignature}
                >
                  <View className="w-10 h-10 bg-green-100 rounded-full items-center justify-center">
                    <Ionicons name="create-outline" size={24} color="#10B981" />
                  </View>
                  <View className="ml-3">
                    <Text className="text-lg font-semibold">自动生成签名</Text>
                    <Text className="text-gray-500">生成签名图片</Text>
                  </View>
                </Pressable>

                <Pressable 
                  className="mt-2 py-3 items-center bg-gray-100 rounded-xl"
                  onPress={() => setShowSignatureModal(false)}
                >
                  <Text className="text-gray-600 font-semibold">取消</Text>
                </Pressable>
              </View>
            )}
          </View>
        </View>
      </Modal>
    );
  };

  // 手写签名模态框
  const renderHandwrittenSignatureModal = () => {
    return (
      <HandwrittenSignature
        visible={showHandwrittenSignatureModal}
        onClose={() => setShowHandwrittenSignatureModal(false)}
        onSave={saveHandwrittenSignature}
      />
    );
  };

  // 收据相关功能
  // 查看收据详情
  const viewReceiptDetail = (receipt: any) => {
    setSelectedReceipt(receipt);
    setShowReceiptDetailModal(true);
  };

  // 编辑收据
  const editReceipt = (receipt: any) => {
    setSelectedReceipt(receipt);
    setEditedReceiptData({
      serialNo: receipt.serialNo,
      amount: receipt.amount,
      date: receipt.date,
      vendor: receipt.vendor,
      category: receipt.category,
      feeType: receipt.feeType || '',
      notes: receipt.notes || '',
    });
    setShowReceiptEditModal(true);
  };

  

  // 删除收据
  const deleteReceipt = async () => {
    if (!receiptToDelete) return;
    
    try {
      const token = await getToken();
      if (!token) {
        throw new Error('认证失败：无法获取token');
      }
      
      const response = await fetch(`${API_BASE_URL}/api/themes/receipts/delete`, {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          serialNo: receiptToDelete,
        }),
      });
      
      const result = await response.json();
      if (result.messageStatus === 'success') {
        // 更新本地状态
        if (theme) {
          const updatedReceipts = theme.receipts.filter(r => r.serialNo !== receiptToDelete);
          setTheme({ 
            ...theme, 
            receipts: updatedReceipts,
            receiptsCount: updatedReceipts.length
          });
        }
        
        Alert.alert('成功', '收据已删除');
      } else {
        throw new Error('删除收据失败');
      }
    } catch (error) {
      console.error('删除收据失败:', error);
      Alert.alert('错误', '删除收据失败');
    } finally {
      setShowDeleteReceiptConfirm(false);
      setReceiptToDelete(null);
    }
  };

  // 收据详情模态框
  const renderReceiptDetailModal = () => {
    if (!selectedReceipt) return null;
    
    return (
      <Modal
        visible={showReceiptDetailModal}
        transparent
        animationType="slide"
        onRequestClose={() => setShowReceiptDetailModal(false)}
      >
        <View className="flex-1 justify-end bg-black/50">
          <View className="bg-white rounded-t-3xl p-6 max-h-5/6">
            <View className="items-center mb-6">
              <View className="w-10 h-1 bg-gray-300 rounded-full mb-2" />
              <Text className="text-xl font-bold">收据详情</Text>
            </View>
            
            <ScrollView className="mb-4">
              <View className="mb-4">
                <Text className="text-sm text-gray-500">商家</Text>
                <Text className="text-lg font-medium">{selectedReceipt.vendor}</Text>
              </View>
              
              <View className="mb-4">
                <Text className="text-sm text-gray-500">金额</Text>
                <Text className="text-lg font-medium">{formatAmount(selectedReceipt.amount)}</Text>
              </View>
              
              <View className="mb-4">
                <Text className="text-sm text-gray-500">日期</Text>
                <Text className="text-lg font-medium">{formatDate(selectedReceipt.date)}</Text>
              </View>
              
              <View className="mb-4">
                <Text className="text-sm text-gray-500">开票</Text>
                <Text className="text-lg font-medium">{selectedReceipt.buyer || '无类别'}</Text>
              </View>
              
              <View className="mb-4">
                <Text className="text-sm text-gray-500">费用类型</Text>
                <Text className="text-lg font-medium">{selectedReceipt.feeType || '无'}</Text>
              </View>
              
              <View className="mb-4">
                <Text className="text-sm text-gray-500">备注</Text>
                <Text className="text-lg font-medium">{selectedReceipt.notes || '无'}</Text>
              </View>
              
              <View className="mb-4">
                <Text className="text-sm text-gray-500">状态</Text>
                <Text className="text-lg font-medium">{selectedReceipt.status}</Text>
              </View>
              
              <View className="mb-4">
                <Text className="text-sm text-gray-500">上传者</Text>
                <Text className="text-lg font-medium">{selectedReceipt.uploaded_by_name}</Text>
              </View>
        
              {selectedReceipt.attachments && selectedReceipt.attachments.length > 0 && (
                <View className="mb-4">
                  <Text className="text-sm text-gray-500 mb-2">附件</Text>
                  {selectedReceipt.attachments.map((attachment: any, index: number) => (
                    <TouchableOpacity 
                      key={index} 
                      className="bg-gray-100 p-3 rounded-lg mb-2 flex-row justify-between items-center"
                      onPress={() => viewAttachment(attachment.serialNo)}
                    >
                      <View className="flex-row items-center">
                        <Ionicons 
                          name={getFileIconName(attachment.fileName)} 
                          size={20} 
                          color="#3B82F6" 
                          className="mr-2" 
                        />
                        <View>
                          <Text className="font-medium">{attachment.fileName}</Text>
                          <Text className="text-sm text-gray-500">
                            {attachment.isReceipt ? '主要发票' : '附件'}
                          </Text>
                        </View>
                      </View>
                      <Ionicons name="eye-outline" size={20} color="#3B82F6" />
                    </TouchableOpacity>
                  ))}
                </View>
              )}
            </ScrollView>
            
            <View className="flex-row mt-2">
              <TouchableOpacity 
                className="flex-1 py-3 bg-gray-200 rounded-lg mr-2 items-center"
                onPress={() => setShowReceiptDetailModal(false)}
              >
                <Text className="font-medium text-gray-700">关闭</Text>
              </TouchableOpacity>
              
              <TouchableOpacity 
                className="flex-1 py-3 bg-blue-500 rounded-lg items-center"
                onPress={() => {
                  setShowReceiptDetailModal(false);
                  editReceipt(selectedReceipt);
                }}
              >
                <Text className="font-medium text-white">编辑</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
        
        {/* 附件查看模态框 */}
        {viewingAttachment && (
          <Modal
            visible={!!viewingAttachment}
            transparent
            animationType="fade"
            onRequestClose={() => setViewingAttachment(null)}
          >
            <View className="flex-1 bg-black justify-center">
              <View className="absolute top-10 right-5 z-10">
                <TouchableOpacity 
                  onPress={() => setViewingAttachment(null)}
                  className="bg-white/20 rounded-full p-2"
                >
                  <Ionicons name="close" size={24} color="white" />
                </TouchableOpacity>
              </View>
              
              <AttachmentViewer 
                attachmentId={viewingAttachment} 
                onClose={() => setViewingAttachment(null)}
              />
            </View>
          </Modal>
        )}
      </Modal>
    );
  };

  // 获取文件图标名称
  const getFileIconName = (fileName: string) => {
    const ext = fileName.split('.').pop()?.toLowerCase();
    
    if (ext === 'pdf') return 'document-text-outline';
    if (['jpg', 'jpeg', 'png', 'gif'].includes(ext || '')) return 'image-outline';
    return 'document-outline';
  };

  // 查看附件
  const viewAttachment = async (attachmentId: string) => {
    console.log('查看附件:', attachmentId);
    // 设置当前查看的附件ID
    setViewingAttachment(attachmentId);
  };

  // 附件查看器组件
  const AttachmentViewer = ({ attachmentId, onClose }: { attachmentId: string, onClose: () => void }) => {
    const [loading, setLoading] = useState(true);
    const [attachmentData, setAttachmentData] = useState<string | null>(null);
    const [error, setError] = useState<string | null>(null);
    const [isPdf, setIsPdf] = useState(false);
    
    useEffect(() => {
      const fetchAttachment = async () => {
        try {
          setLoading(true);
          setError(null);
          
          // 获取token
          const token = await getToken();
          if (!token) {
            throw new Error('认证失败：无法获取token');
          }
          
          // 获取附件文件名来判断类型
          const fileName = selectedReceipt?.attachments.find(
            (a: {serialNo: string, fileName: string}) => a.serialNo === attachmentId
          )?.fileName || '';
          
          setIsPdf(fileName.toLowerCase().endsWith('.xls')||fileName.toLowerCase().endsWith('.xlsx')||fileName.toLowerCase().endsWith('.doc')||fileName.toLowerCase().endsWith('.docx'));
          
          // 修正附件查看URL
          const url = `${API_BASE_URL}/api/receipts/attachment/get?serialNo=${attachmentId}&token=${encodeURIComponent(token)}`;
          
          // 发送请求获取附件数据
          const response = await fetch(url, {
            method: 'GET',
            headers: {
              'Authorization': `Bearer ${token}`
            }
          });

          console.log('获取附件响应:', response);
          
          if (!response.ok) {
            throw new Error(`无法获取附件: ${response.status}`);
          }
          
          // 处理不同类型的附件
          if (isPdf) {
            // 对于PDF，只存储URL用于外部打开
            setAttachmentData(url);
            setLoading(false);
          } else {
            // 对于图片，转换为base64数据
            const blob = await response.blob();
            const reader = new FileReader();
            
            reader.onload = () => {
              const base64data = reader.result as string;
              setAttachmentData(base64data);
              setLoading(false);
            };
            
            reader.onerror = () => {
              setError('读取附件数据失败');
              setLoading(false);
            };
            
            reader.readAsDataURL(blob);
            return; // 因为读取是异步的，所以这里返回，避免下面的setLoading(false)被调用
          }
        } catch (err) {
          console.error('获取附件失败:', err);
          setError('无法加载附件');
        } finally {
          if (!isPdf) {
            setLoading(false); // 对于PDF，已经在reader.onload中设置了loading状态
          }
        }
      };
      
      fetchAttachment();
    }, [attachmentId, isPdf, selectedReceipt]);
    
    if (loading) {
      return (
        <View className="flex-1 justify-center items-center">
          <ActivityIndicator size="large" color="white" />
          <Text className="text-white mt-4">加载附件中...</Text>
        </View>
      );
    }
    
    if (error) {
      return (
        <View className="flex-1 justify-center items-center p-4">
          <Ionicons name="alert-circle-outline" size={48} color="white" />
          <Text className="text-white mt-4 text-center">{error}</Text>
          <TouchableOpacity
            className="mt-4 bg-white/20 px-4 py-2 rounded-lg"
            onPress={onClose}
          >
            <Text className="text-white">关闭</Text>
          </TouchableOpacity>
        </View>
      );
    }
    
    return (
      <View className="flex-1 justify-center items-center">
        {isPdf ? (
          <View className="flex-1 justify-center items-center p-4">
            <Ionicons name="document-text" size={48} color="white" />
            <Text className="text-white mt-4 text-center">PDF文件不支持在应用内预览</Text>
            <TouchableOpacity
              className="mt-4 bg-blue-500 px-4 py-2 rounded-lg"
              onPress={() => {
                if (attachmentData) {
                  Linking.openURL(attachmentData);
                }
              }}
            >
              <Text className="text-white">在浏览器中打开</Text>
            </TouchableOpacity>
          </View>
        ) : (
          <Image
            source={{ uri: attachmentData || '' }}
            className="flex-1 w-full"
            resizeMode="contain"
            onError={() => setError('图片加载失败')}
          />
        )}
      </View>
    );
  };

  // 收据编辑模态框
  const renderReceiptEditModal = () => {
    if (!editedReceiptData) return null;
    
    return (
      <Modal
        visible={showReceiptEditModal}
        transparent
        animationType="slide"
        onRequestClose={() => setShowReceiptEditModal(false)}
      >
        <View className="flex-1 justify-end bg-black/50">
          <View className="bg-white rounded-t-3xl p-6 max-h-5/6">
            <View className="items-center mb-6">
              <View className="w-10 h-1 bg-gray-300 rounded-full mb-2" />
              <Text className="text-xl font-bold">编辑收据</Text>
            </View>
            
            <ScrollView className="mb-4">
              <View className="mb-4">
                <Text className="text-sm text-gray-500 mb-1">商家</Text>
                <TextInput
                  className="border border-gray-300 rounded-lg px-3 py-2"
                  value={editedReceiptData.vendor}
                  onChangeText={(text) => setEditedReceiptData({...editedReceiptData, vendor: text})}
                />
              </View>

              <View className="mb-4">
                <Text className="text-sm text-gray-500 mb-1">开票</Text>
                <TextInput
                  className="border border-gray-300 rounded-lg px-3 py-2"
                  value={editedReceiptData.buyer}
                  onChangeText={(text) => setEditedReceiptData({...editedReceiptData, buyer: text})}
                />
              </View>
              
              <View className="mb-4">
                <Text className="text-sm text-gray-500 mb-1">金额</Text>
                <TextInput
                  className="border border-gray-300 rounded-lg px-3 py-2"
                  value={String(editedReceiptData.amount)}
                  keyboardType="numeric"
                  onChangeText={(text) => {
                    const amount = parseFloat(text) || 0;
                    setEditedReceiptData({...editedReceiptData, amount});
                  }}
                />
              </View>
              
              <View className="mb-4">
                <Text className="text-sm text-gray-500 mb-1">日期</Text>
                <TextInput
                  className="border border-gray-300 rounded-lg px-3 py-2"
                  value={editedReceiptData.date}
                  placeholder="YYYY-MM-DD"
                  onChangeText={(text) => setEditedReceiptData({...editedReceiptData, date: text})}
                />
              </View>
              
              <View className="mb-4">
                <Text className="text-sm text-gray-500 mb-1">名目</Text>
                <TextInput
                  className="border border-gray-300 rounded-lg px-3 py-2"
                  value={editedReceiptData.category}
                  onChangeText={(text) => setEditedReceiptData({...editedReceiptData, category: text})}
                />
              </View>
              
              <View className="mb-4">
                <Text className="text-sm text-gray-500 mb-1">费用类型</Text>
                <View className="border border-gray-300 rounded-lg overflow-hidden">
                  <Picker
                    selectedValue={editedReceiptData.feeType}
                    onValueChange={(value) => setEditedReceiptData({...editedReceiptData, feeType: value})}
                  >
                    <Picker.Item label="交通费" value="交通费" />
                    <Picker.Item label="通讯费" value="通讯费" />
                    <Picker.Item label="住宿费" value="住宿费" />
                    <Picker.Item label="餐饮费" value="餐饮费" />
                    <Picker.Item label="其他" value="其他" />
                  </Picker>
                </View>
              </View>
              
              <View className="mb-4">
                <Text className="text-sm text-gray-500 mb-1">备注</Text>
                <TextInput
                  className="border border-gray-300 rounded-lg px-3 py-2"
                  value={editedReceiptData.notes}
                  multiline
                  numberOfLines={3}
                  textAlignVertical="top"
                  onChangeText={(text) => setEditedReceiptData({...editedReceiptData, notes: text})}
                />
              </View>
              
              {/* 附件管理部分 */}
              <View className="mb-4">
                <View className="flex-row justify-between items-center mb-2">
                  <Text className="text-sm text-gray-500">附件</Text>
                  <TouchableOpacity 
                    className="bg-blue-100 px-2 py-1 rounded-lg"
                    onPress={() => setShowAttachmentActions(true)}
                  >
                    <Text className="text-blue-600 text-sm">添加附件</Text>
                  </TouchableOpacity>
                </View>
                
                {attachments.length === 0 ? (
                  <View className="border border-dashed border-gray-300 rounded-lg p-4 items-center justify-center">
                    <Ionicons name="document-outline" size={24} color="#9CA3AF" />
                    <Text className="text-gray-500 mt-2">暂无附件</Text>
                    <TouchableOpacity 
                      className="mt-2 bg-gray-100 px-3 py-1 rounded-lg"
                      onPress={() => setShowAttachmentActions(true)}
                    >
                      <Text className="text-gray-700">添加附件</Text>
                    </TouchableOpacity>
                  </View>
                ) : (
                  attachments.map((attachment, index) => (
                    <View 
                      key={index}
                      className="flex-row justify-between items-center bg-gray-100 p-3 rounded-lg mb-2"
                    >
                      <View className="flex-row items-center flex-1">
                        <Ionicons 
                          name={getFileIconName(attachment.fileName)} 
                          size={20} 
                          color="#3B82F6" 
                          className="mr-2" 
                        />
                        <View className="flex-1">
                          <Text className="font-medium" numberOfLines={1}>{attachment.fileName}</Text>
                          <Text className="text-xs text-gray-500">
                            {attachment.isReceipt ? '主要发票' : '附件'}
                          </Text>
                        </View>
                      </View>
                      
                      <View className="flex-row">
                        <TouchableOpacity 
                          className="p-2"
                           onPress={() => viewAttachment(attachment.serialNo)}
                        >
                          <Ionicons name="eye-outline" size={18} color="#3B82F6" />
                        </TouchableOpacity>
                        
                        {
                          attachment.isReceipt ? (<></>): (
                       
                        <TouchableOpacity 
                          className="p-2"
                          onPress={() => handleRemoveAttachment(index)}
                        >
                          <Ionicons name="trash-outline" size={18} color="#EF4444" />
                        </TouchableOpacity>
                            )
                        }
                      </View>
                    </View>
                  ))
                )}
              </View>
            </ScrollView>
            
            <View className="flex-row mt-2">
              <TouchableOpacity 
                className="flex-1 py-3 bg-gray-200 rounded-lg mr-2 items-center"
                onPress={() => setShowReceiptEditModal(false)}
              >
                <Text className="font-medium text-gray-700">取消</Text>
              </TouchableOpacity>
              
              <TouchableOpacity 
                className="flex-1 py-3 bg-blue-500 rounded-lg items-center"
                onPress={() => handleSaveEditedReceipt()}
              >
                <Text className="font-medium text-white">保存</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
        
        {/* 附件查看模态框 */}
        {viewingAttachment && (
          <Modal
            visible={!!viewingAttachment}
            transparent
            animationType="fade"
            onRequestClose={() => setViewingAttachment(null)}
          >
            <View className="flex-1 bg-black justify-center">
              <View className="absolute top-10 right-5 z-10">
                <TouchableOpacity 
                  onPress={() => setViewingAttachment(null)}
                  className="bg-white/20 rounded-full p-2"
                >
                  <Ionicons name="close" size={24} color="white" />
                </TouchableOpacity>
              </View>
              
              <AttachmentViewer 
                attachmentId={viewingAttachment} 
                onClose={() => setViewingAttachment(null)}
              />
            </View>
          </Modal>
        )}
        
        {/* 附件操作选择模态框 */}
        <Modal
          visible={showAttachmentActions}
          transparent
          animationType="slide"
          onRequestClose={() => setShowAttachmentActions(false)}
        >
          <View className="flex-1 justify-end bg-black/50">
            <View className="bg-white rounded-t-3xl p-6">
              <View className="items-center mb-6">
                <View className="w-10 h-1 bg-gray-300 rounded-full mb-2" />
                <Text className="text-xl font-bold">添加附件</Text>
              </View>
              
              <View className="gap-4">
                <Pressable 
                  className="flex-row items-center p-4 bg-blue-50 rounded-xl"
                  onPress={() => handleAddAttachment('document')}
                >
                  <View className="w-10 h-10 bg-blue-100 rounded-full items-center justify-center">
                    <Ionicons name="document-outline" size={24} color="#3B82F6" />
                  </View>
                  <View className="ml-3">
                    <Text className="text-lg font-semibold">从文件中选择</Text>
                    <Text className="text-gray-500">选择PDF或图片文件</Text>
                  </View>
                </Pressable>
                
                <Pressable 
                  className="flex-row items-center p-4 bg-green-50 rounded-xl"
                  onPress={() => handleAddAttachment('gallery')}
                >
                  <View className="w-10 h-10 bg-green-100 rounded-full items-center justify-center">
                    <Ionicons name="images-outline" size={24} color="#10B981" />
                  </View>
                  <View className="ml-3">
                    <Text className="text-lg font-semibold">从相册中选择</Text>
                    <Text className="text-gray-500">选择图片附件</Text>
                  </View>
                </Pressable>
                
                <Pressable 
                  className="flex-row items-center p-4 bg-purple-50 rounded-xl"
                  onPress={() => handleAddAttachment('camera')}
                >
                  <View className="w-10 h-10 bg-purple-100 rounded-full items-center justify-center">
                    <Ionicons name="camera-outline" size={24} color="#8B5CF6" />
                  </View>
                  <View className="ml-3">
                    <Text className="text-lg font-semibold">拍照</Text>
                    <Text className="text-gray-500">使用相机拍摄照片</Text>
                  </View>
                </Pressable>
                
                <Pressable 
                  className="mt-2 py-3 items-center bg-gray-100 rounded-xl"
                  onPress={() => setShowAttachmentActions(false)}
                >
                  <Text className="text-gray-600 font-semibold">取消</Text>
                </Pressable>
              </View>
            </View>
          </View>
        </Modal>
      </Modal>
    );
  };
  
  // 处理删除附件
  const handleRemoveAttachment = (index: number) => {
    Alert.alert(
      '删除附件',
      '确定要删除这个附件吗？',
      [
        {
          text: '取消',
          style: 'cancel'
        },
        {
          text: '删除',
          style: 'destructive',
          onPress: () => {
            // 更新全局附件状态
            const updatedAttachments = [...attachments];
            updatedAttachments.splice(index, 1);
            setAttachments(updatedAttachments);
          }
        }
      ]
    );
  };
  
  // 处理添加附件
  const handleAddAttachment = async (source: 'document' | 'gallery' | 'camera') => {
    try {
      let result;
      
      if (source === 'document') {
        result = await DocumentPicker.getDocumentAsync({
          type: ['image/*', 'application/pdf'],
          copyToCacheDirectory: true
        });
        
        if (!result.canceled && result.assets && result.assets.length > 0) {
          await handleUploadAttachment(result.assets[0].uri, result.assets[0].name);
        }
      } else if (source === 'gallery') {
        result = await ImagePicker.launchImageLibraryAsync({
          mediaTypes: ImagePicker.MediaTypeOptions.Images,
          allowsEditing: false,
          quality: 0.8,
        });
        
        if (!result.canceled && result.assets && result.assets.length > 0) {
          const asset = result.assets[0];
          const fileName = asset.fileName || `image_${new Date().getTime()}.jpg`;
          await handleUploadAttachment(asset.uri, fileName);
        }
      } else if (source === 'camera') {
        const { status } = await ImagePicker.requestCameraPermissionsAsync();
        if (status !== 'granted') {
          Alert.alert('权限错误', '需要相机权限才能拍照');
          return;
        }
        
        result = await ImagePicker.launchCameraAsync({
          mediaTypes: ImagePicker.MediaTypeOptions.Images,
          allowsEditing: false,
          quality: 0.8,
        });
        
        if (!result.canceled && result.assets && result.assets.length > 0) {
          const fileName = `camera_${new Date().getTime()}.jpg`;
          await handleUploadAttachment(result.assets[0].uri, fileName);
        }
      }
      
      setShowAttachmentActions(false);
    } catch (error) {
      console.error('选择附件失败:', error);
      Alert.alert('错误', '选择附件失败');
    }
  };
  
  // 上传附件
  const handleUploadAttachment = async (uri: string, fileName: string) => {
    if (!selectedReceipt) return;
    
    try {
      Alert.alert('上传中', '正在上传附件，请稍候...');
      
      const formData = new FormData();
      const uriParts = uri.split('.');
      const fileType = uriParts[uriParts.length - 1].toLowerCase();
      
      // 确定文件类型
      let fileTypeStr = 'image/jpeg';
      if (fileType === 'pdf') {
        fileTypeStr = 'application/pdf';
      } else if (fileType === 'png') {
        fileTypeStr = 'image/png';
      }
      
      console.log('准备上传附件:', {
        uri,
        fileName,
        fileType: fileTypeStr,
        receiptSerialNo: selectedReceipt.serialNo,
      });

      const token = await getToken();
      if (!token) {
        throw new Error('认证失败：无法获取token');
      }

      // 修正API端点路径
      const uploadUrl = `${API_BASE_URL}/api/receipts/attachment/upload`;




      console.log('上传附件URL:', uploadUrl);
      

           // 使用Expo的文件系统API上传
      const uploadResult = await FileSystem.uploadAsync(
      uploadUrl,
      uri,
      {
        httpMethod: 'POST',
        uploadType: FileSystem.FileSystemUploadType.MULTIPART,
        fieldName: 'file', // 文件字段名
        mimeType: uri.endsWith('.pdf') ? 'application/pdf' : uri.endsWith('.png') ? 'image/png' : 'image/jpeg',
        parameters: {
          'receiptSerialNo': selectedReceipt.serialNo,
          'remark': 'APP编辑添加的附件',
          'isReceipt': 'false'
        },
        headers: {
          'Authorization': `Bearer ${token}`,
          'Accept': 'application/json'
        }
      }
      );


      console.log('上传响应状态:', uploadResult.status);
      
      // 解析响应
      const result = JSON.parse(uploadResult.body);
      console.log('上传响应:', result);
      
      if (result.messageStatus === 'success') {
             // 添加新上传的附件到列表
         const newAttachment = {
          serialNo: result.data,
          fileName: fileName,
          isReceipt: false
        };
        
        // 更新全局附件状态
        setAttachments([...attachments, newAttachment]);
        
        Alert.alert('成功', '附件上传成功');
        Alert.alert('成功', '收据上传成功');
      } else {
        throw new Error(result.message || '上传附件失败');
      }
      

    } catch (error: any) {
      console.error('上传附件失败详细信息:', error);
      let errorMessage = '上传附件失败';
      
      if (error.message) {
        errorMessage += `: ${error.message}`;
      }
      
      Alert.alert('错误', errorMessage);
    } finally {
      setShowAttachmentActions(false);
    }
  };
  
  // 保存编辑后的收据（包含附件）
  const handleSaveEditedReceipt = async () => {
    if (!editedReceiptData || !selectedReceipt) return;
    
    try {
      
      const token = await getToken();
      if (!token) {
        throw new Error('认证失败：无法获取token');
      }
      
      const response = await fetch(`${API_BASE_URL}/api/themes/receipts/update`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          ...editedReceiptData,
          serialNo: selectedReceipt.serialNo,
          attachments: attachments,
        }),
      });
      
      const result = await response.json();
      if (result.messageStatus === 'success') {
        // 更新本地状态
        if (theme) {
          const updatedReceipts = theme.receipts.map(r => 
            r.serialNo === editedReceiptData.serialNo ? 
              { ...r, ...editedReceiptData, attachments } : r
          );
          
          setTheme({ ...theme, receipts: updatedReceipts });
        }
        
        Alert.alert('成功', '收据已更新');
        setShowReceiptEditModal(false);
        setSelectedReceipt(null);
        setEditedReceiptData(null);
      } else {
        throw new Error('更新收据失败');
      }
    } catch (error) {
      console.error('更新收据失败:', error);
      Alert.alert('错误', '更新收据失败');
    }
  };

  // 下载所有收据函数
  const downloadAllReceipts = async () => {
    if (!theme || theme.receipts.length === 0) {
      Alert.alert('提示', '没有可下载的收据');
      return;
    }
    
    try {
      // 显示加载状态
      Alert.alert('提示', '即将打开浏览器下载页面...');
      
      const token = await getToken();
      if (!token) {
        throw new Error('认证失败：无法获取token');
      }
      
      // 创建URL查询参数
      const queryParams = new URLSearchParams();
      queryParams.append('themeSerialNo', id as string);
      queryParams.append('title', theme.title);
      
      // 获取所有收据的序列号
      theme.receipts.forEach(receipt => {
        queryParams.append('serialNos', receipt.serialNo);
      });
      
      // 构建下载URL
      const downloadUrl = `${API_BASE_URL}/api/themes/download-all?${queryParams.toString()}`;
      
      // 在浏览器中打开下载链接，添加认证头
      const downloadUrlWithAuth = `${downloadUrl}&token=${encodeURIComponent(token)}`;
      const supported = await Linking.canOpenURL(downloadUrlWithAuth);
      
      if (supported) {
        await Linking.openURL(downloadUrlWithAuth);
      } else {
        Alert.alert('错误', '无法打开浏览器下载链接');
      }
    } catch (error: any) {
      console.error('下载报销凭证汇总时出错:', error);
      Alert.alert('错误', `下载失败: ${error.message || '未知错误'}`);
    }
  };

  // 渲染主题详情
  const renderContent = () => {
    if (loading && !refreshing) {
      return (
        <View className="flex-1 justify-center items-center">
          <ActivityIndicator size="large" color="#3B82F6" />
          <Text className="mt-2 text-gray-500">加载中...</Text>
        </View>
      );
    }

    if (error) {
      return (
        <View className="flex-1 justify-center items-center p-4">
          <Ionicons name="alert-circle-outline" size={48} color="#EF4444" />
          <Text className="mt-2 text-gray-700 text-center">{error}</Text>
          <TouchableOpacity 
            className="mt-4 bg-blue-500 px-4 py-2 rounded-lg"
            onPress={loadThemeDetail}
          >
            <Text className="text-white font-medium">重试</Text>
          </TouchableOpacity>
        </View>
      );
    }

    if (!theme) {
      return (
        <View className="flex-1 justify-center items-center p-4">
          <Ionicons name="document-outline" size={48} color="#9CA3AF" />
          <Text className="mt-2 text-gray-700 text-center">未找到主题信息</Text>
          <TouchableOpacity 
            className="mt-4 bg-blue-500 px-4 py-2 rounded-lg"
            onPress={() => router.back()}
          >
            <Text className="text-white font-medium">返回</Text>
          </TouchableOpacity>
        </View>
      );
    }

    return (
      <ScrollView 
        className="flex-1"
        refreshControl={
          <RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />
        }
      >
        {/* 主题信息卡片 */}
        <LinearGradient
          colors={['#3B82F6', '#2563EB']}
          className="rounded-lg shadow-md mb-4 overflow-hidden"
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
        >
          <View className="p-5">
            <View className="flex-row justify-between items-center mb-3">
              <Text className="font-bold text-white text-xl">{theme.title}</Text>
              <View 
                className="px-2 py-1 rounded-full bg-white/20"
              >
                <Text className="text-xs font-medium text-white">
                  {theme.status === 'active' ? '进行中' : '已完成'}
                </Text>
              </View>
            </View>
            
            <Text className="text-white/90 mb-5">{theme.description}</Text>
            
            <View className="flex-row justify-between mb-3">
              <View className="flex-1 mr-2">
                <Text className="text-white/70 text-xs">创建日期</Text>
                <View className="flex-row items-center mt-1">
                  <Ionicons name="calendar-outline" size={14} color="white" />
                  <Text className="text-white ml-1">{formatDate(theme.createTime)}</Text>
                </View>
              </View>
              
              <View className="flex-1 mr-2">
                <Text className="text-white/70 text-xs">创建人</Text>
                <View className="flex-row items-center mt-1">
                  <Ionicons name="person-outline" size={14} color="white" />
                  <Text className="text-white ml-1">{theme.creator_name || '未知'}</Text>
                </View>
              </View>
              
              <View className="flex-1">
                <Text className="text-white/70 text-xs">收据数量</Text>
                <View className="flex-row items-center mt-1">
                  <Ionicons name="document-outline" size={14} color="white" />
                  <Text className="text-white ml-1">{theme.receiptsCount || 0}</Text>
                </View>
              </View>
            </View>
            
            <View className="bg-white/10 p-3 rounded-lg">
              <Text className="text-white/70 text-xs">总金额</Text>
              <Text className="font-bold text-white text-xl">{formatAmount(theme.totalAmount || 0)}</Text>
            </View>
          </View>
        </LinearGradient>
        
        {/* 操作按钮区域 */}
        <View className="flex-row justify-between px-4 mb-4">
          {theme.receipts && theme.receipts.length > 0 && (
            <TouchableOpacity 
              className="bg-green-500 rounded-lg py-2 px-4 flex-row items-center shadow-sm flex-1"
              onPress={downloadAllReceipts}
            >
              <Ionicons name="download-outline" size={20} color="white" />
              <Text className="text-white font-medium ml-2">下载全部收据</Text>
            </TouchableOpacity>
          )}
        </View>
        
        {/* 签名区域 */}
        <View className="bg-white rounded-lg shadow-sm p-4 mb-4">
          <View className="flex-row justify-between items-center mb-3">
            <View className="flex-row items-center">
              <Ionicons name="create-outline" size={20} color="#3B82F6" className="mr-1" />
              <Text className="font-bold text-gray-800 text-lg">签名</Text>
            </View>
            
            {theme?.signature && (
              <TouchableOpacity onPress={() => setShowSignature(!showSignature)}>
                <Ionicons 
                  name={showSignature ? "eye-off-outline" : "eye-outline"} 
                  size={20} 
                  color="#3B82F6" 
                />
              </TouchableOpacity>
            )}
          </View>
          
          {theme?.signature ? (
            showSignature ? (
              <View className="items-center">
                <Image 
                  source={{ uri: theme.signature.signatureData }} 
                  className="h-16 w-48 object-contain" 
                  resizeMode="contain"
                />
                {isThemeAdmin() && (
                  <TouchableOpacity 
                    className="mt-3 bg-blue-100 px-3 py-1 rounded-lg"
                    onPress={() => setShowSignatureModal(true)}
                  >
                    <Text className="text-blue-600">修改签名</Text>
                  </TouchableOpacity>
                )}
              </View>
            ) : (
              <TouchableOpacity 
                className="h-16 bg-gray-100 rounded-lg items-center justify-center"
                onPress={() => setShowSignature(true)}
              >
                <Text className="text-gray-500">点击查看签名</Text>
              </TouchableOpacity>
            )
          ) : isThemeAdmin() ? (
            <TouchableOpacity 
              className="h-16 bg-gray-100 rounded-lg items-center justify-center"
              onPress={() => setShowSignatureModal(true)}
            >
              <Text className="text-gray-500">点击添加签名</Text>
            </TouchableOpacity>
          ) : (
            <View className="h-16 bg-gray-100 rounded-lg items-center justify-center">
              <Text className="text-gray-500">暂无签名</Text>
            </View>
          )}
        </View>
        
        {/* OA编号区域 */}
        <View className="bg-white rounded-lg shadow-sm p-4 mb-4">
          <View className="flex-row justify-between items-center">
            <View className="flex-row items-center">
              <Ionicons name="document-text-outline" size={20} color="#3B82F6" className="mr-1" />
              <Text className="font-bold text-gray-800 text-lg">OA编号</Text>
            </View>
            
            {isAdmin() && !isEditingOa && (
              <TouchableOpacity 
                onPress={() => {
                  setOaValue(theme.oa || '');
                  setIsEditingOa(true);
                }}
              >
                <Ionicons name="pencil-outline" size={20} color="#3B82F6" />
              </TouchableOpacity>
            )}
          </View>
          
          {isEditingOa ? (
            <View className="mt-3">
              <TextInput
                value={oaValue}
                onChangeText={setOaValue}
                placeholder="请输入OA编号"
                className="border border-gray-300 rounded-lg px-3 py-2 mb-2"
              />
              <View className="flex-row justify-end">
                <TouchableOpacity 
                  className="bg-gray-200 px-3 py-1 rounded-lg mr-2"
                  onPress={() => setIsEditingOa(false)}
                >
                  <Text className="text-gray-700">取消</Text>
                </TouchableOpacity>
                <TouchableOpacity 
                  className="bg-blue-500 px-3 py-1 rounded-lg"
                  onPress={handleSaveOa}
                >
                  <Text className="text-white">保存</Text>
                </TouchableOpacity>
              </View>
            </View>
          ) : (
            <View className="mt-2">
              <Text className="text-gray-700">
                {theme.oa ? theme.oa : '暂无OA编号'}
              </Text>
            </View>
          )}
        </View>
        
        {/* 参与者部分 */}
        <View className="bg-white rounded-lg shadow-sm p-4 mb-4">
          <View className="flex-row justify-between items-center mb-3">
            <View className="flex-row items-center">
              <Ionicons name="people-outline" size={20} color="#3B82F6" className="mr-1" />
              <Text className="font-bold text-gray-800 text-lg">参与者</Text>
            </View>
            <View className="flex-row items-center">
              <Text className="text-gray-500 text-sm mr-2">{theme.participants?.length || 0}人</Text>
              <TouchableOpacity onPress={() => setParticipantsExpanded(!participantsExpanded)}>
                <Ionicons 
                  name={participantsExpanded ? "chevron-up-circle" : "chevron-down-circle"} 
                  size={20} 
                  color="#3B82F6" 
                />
              </TouchableOpacity>
            </View>
          </View>
          {renderParticipants()}
        </View>
        
        {/* 收据列表部分 - 修改以支持详情、编辑和删除功能 */}
        <View className="bg-white rounded-lg shadow-sm p-4 mb-4">
          <View className="flex-row justify-between items-center mb-3">
            <View className="flex-row items-center">
              <Ionicons name="receipt-outline" size={20} color="#3B82F6" className="mr-1" />
              <Text className="font-bold text-gray-800 text-lg">发票列表</Text>
            </View>
            
            <TouchableOpacity
              className="bg-blue-500 px-3 py-1 rounded-lg flex-row items-center"
              onPress={() => setUploadModalVisible(true)}
            >
              <Ionicons name="add" size={18} color="white" />
              <Text className="text-white font-medium ml-1">添加</Text>
            </TouchableOpacity>
          </View>
          
          {/* 修改收据列表渲染，添加详情、编辑和删除功能 */}
          {renderReceipts()}
        </View>
      </ScrollView>
    );
  };

  // 修改渲染收据列表的函数，添加详情、编辑和删除功能
  const renderReceipts = () => {
    if (!theme?.receipts || theme.receipts.length === 0) {
      return (
        <View className="py-8 items-center">
          <Ionicons name="receipt-outline" size={48} color="#9CA3AF" />
          <Text className="text-gray-500 italic mt-2">暂无收据</Text>
          <TouchableOpacity 
            className="mt-4 bg-blue-500 px-4 py-2 rounded-lg"
            onPress={() => setUploadModalVisible(true)}
          >
            <Text className="text-white font-medium">添加收据</Text>
          </TouchableOpacity>
        </View>
      );
    }

    return (
      <View className="py-2">
        {theme.receipts.map((receipt, index) => (
          <View 
            key={index} 
            className="mb-4 bg-white rounded-xl p-4 border border-gray-100 shadow-sm"
          >
            <View className="flex-row justify-between items-center mb-3">
              <View className="flex-row items-center">
                <View className="w-10 h-10 rounded-full bg-blue-50 items-center justify-center mr-2">
                  <Ionicons name="receipt-outline" size={20} color="#3B82F6" />
                </View>
                <Text className="font-semibold text-gray-800 text-lg">{
                
                receipt.vendor && receipt.vendor.length > 10 ? receipt.vendor.slice(0, 10) + '...' : receipt.vendor

                || '未知商家'}</Text>
              </View>
              <Text className="font-bold text-blue-600 text-lg">{receipt.amount}</Text>
            </View>
            
            <View className="flex-row mb-3">
              <View className="flex-row items-center mr-4">
                <Ionicons name="calendar-outline" size={16} color="#6B7280" className="mr-1" />
                <Text className="text-gray-500">{formatDate(receipt.date)}</Text>
              </View>
              <View className="flex-row items-center">
                <Ionicons name="pricetag-outline" size={16} color="#6B7280" className="mr-1" />
                <Text className="text-gray-500">{
                                receipt.category && receipt.category.length > 10 ? receipt.category.slice(0, 10) + '...' : receipt.category

                
                || '无类别'}</Text>
              </View>
            </View>
            
            <View className="flex-row justify-between items-center pt-2 border-t border-gray-100">
              <View className="flex-row items-center">
                <Ionicons name="person-outline" size={16} color="#6B7280" className="mr-1" />
                <Text className="text-gray-500 text-sm">上传者: {receipt.uploaded_by_name}</Text>
              </View>
              <View className="flex-row items-center">

               {
                receipt.status == 'active'?(<Text className="text-green-500 text-sm">状态: {receipt.status}</Text> ):(<Text className="text-gray-500 text-sm">状态: {receipt.status}</Text>)

               }  
              
              
              </View>
              <View className="flex-row">
                <TouchableOpacity 
                  className="mx-1"
                  onPress={() => viewReceiptDetail(receipt)}
                >
                  <Ionicons name="eye-outline" size={22} color="#3B82F6" />
                </TouchableOpacity>
                
                <TouchableOpacity 
                  className="mx-1"
                  onPress={() => editReceipt(receipt)}
                >
                  <Ionicons name="create-outline" size={22} color="#10B981" />
                </TouchableOpacity>
                
                <TouchableOpacity 
                  className="mx-1"
                  onPress={() => {
                    setReceiptToDelete(receipt.serialNo);
                    setShowDeleteReceiptConfirm(true);
                  }}
                >
                  <Ionicons name="trash-outline" size={22} color="#EF4444" />
                </TouchableOpacity>
              </View>
            </View>
          </View>
        ))}
      </View>
    );
  };

  // 判断当前用户是否是管理员
  const isAdmin = () => {
    return auth?.user?.role === 'admin';
  };

  // 判断当前用户是否是主题的管理员
  const isThemeAdmin = () => {
    if (!auth?.user?.userId || !theme) return false;
    if (isAdmin()) return true;
    if (auth.user && theme.userId === auth.user.userId) return true;
    return theme.participants.some(p => p.userId === auth.user?.userId && p.role === 'admin');
  };

  // 保存OA编号
  const handleSaveOa = async () => {
    if (!oaValue.trim()) {
      Alert.alert('提示', 'OA编号不能为空');
      return;
    }
    
    try {
      const token = await getToken();
      if (!token) {
        throw new Error('认证失败：无法获取token');
      }
      
      const response = await fetch(`${API_BASE_URL}/api/themes/update-oa`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          themeSerialNo: id,
          oa: oaValue.trim()
        }),
      });
      
      const result = await response.json();
      if (result.messageStatus === 'success') {
        Alert.alert('成功', 'OA编号已更新');
        setTheme(prevTheme => prevTheme ? { ...prevTheme, oa: oaValue.trim() } : prevTheme);
        setIsEditingOa(false);
        setOaValue('');
      } else {
        Alert.alert('错误', '更新OA编号失败');
      }
    } catch (error) {
      console.error('Error updating OA:', error);
      Alert.alert('错误', '更新OA编号失败');
    }
  };

  // 渲染参与者列表
  const renderParticipants = () => {
    if (!theme?.participants || theme.participants.length === 0) {
      return (
        <View className="py-3">
          <Text className="text-gray-500 italic">暂无参与者</Text>
          {isThemeAdmin() && (
            <View className="flex-row mt-3">
              <TouchableOpacity 
                className="bg-blue-500 px-3 py-2 rounded-lg mr-2 flex-row items-center"
                onPress={() => setShowAddParticipantModal(true)}
              >
                <Ionicons name="person-add" size={16} color="white" />
                <Text className="text-white ml-1">添加参与者</Text>
              </TouchableOpacity>
              <TouchableOpacity 
                className="bg-purple-500 px-3 py-2 rounded-lg flex-row items-center"
                onPress={() => setShowAddProxyModal(true)}
              >
                <Ionicons name="person-add" size={16} color="white" />
                <Text className="text-white ml-1">添加代理人</Text>
              </TouchableOpacity>
            </View>
          )}
        </View>
      );
    }

    // 如果是收缩状态，只显示前两个参与者
    const displayParticipants = participantsExpanded 
      ? theme.participants 
      : theme.participants.slice(0, 2);

    return (
      <View className="py-2">
        {isThemeAdmin() && (
          <View className="flex-row mb-3">
            <TouchableOpacity 
              className="bg-blue-500 px-3 py-2 rounded-lg mr-2 flex-row items-center"
              onPress={() => setShowAddParticipantModal(true)}
            >
              <Ionicons name="person-add" size={16} color="white" />
              <Text className="text-white ml-1">添加参与者</Text>
            </TouchableOpacity>
            <TouchableOpacity 
              className="bg-purple-500 px-3 py-2 rounded-lg flex-row items-center"
              onPress={() => setShowAddProxyModal(true)}
            >
              <Ionicons name="person-add" size={16} color="white" />
              <Text className="text-white ml-1">添加代理人</Text>
            </TouchableOpacity>
          </View>
        )}
        
        {displayParticipants.map((participant, index) => (
          <View key={index} className="flex-row items-center py-3 border-b border-gray-100">
            <View className="w-10 h-10 rounded-full bg-blue-100 items-center justify-center mr-3">
              <Text className="text-blue-600 font-bold">
                {participant.name.charAt(0).toUpperCase()}
              </Text>
            </View>
            <View className="flex-1">
              <Text className="text-gray-800 font-medium">{participant.name}</Text>
              <Text className="text-gray-500 text-sm">{participant.email}</Text>
            </View>
            <View className="flex-row items-center">
              <View 
                className="px-2 py-1 rounded-full mr-2"
                style={{ 
                  backgroundColor: 
                    participant.role === 'admin' 
                      ? '#3B82F620' 
                      : participant.role === 'proxy'
                        ? '#8B5CF620'
                        : '#6B72801A' 
                }}
              >
                <Text 
                  className="text-xs font-medium"
                  style={{ 
                    color: 
                      participant.role === 'admin' 
                        ? '#3B82F6' 
                        : participant.role === 'proxy'
                          ? '#8B5CF6'
                          : '#6B7280' 
                  }}
                >
                  {getRoleName(participant.role)}
                </Text>
              </View>
              
              {isThemeAdmin() && participant.role !== 'admin' && (
                <TouchableOpacity 
                  onPress={() => {
                    setParticipantToDelete(participant.userId);
                    setShowParticipantDeleteConfirm(true);
                  }}
                >
                  <Ionicons name="close-circle" size={20} color="#EF4444" />
                </TouchableOpacity>
              )}
            </View>
          </View>
        ))}

        {theme.participants.length > 2 && (
          <TouchableOpacity 
            className="flex-row items-center justify-center py-3 mt-1"
            onPress={() => setParticipantsExpanded(!participantsExpanded)}
          >
            <Text className="text-blue-500 font-medium mr-1">
              {participantsExpanded ? '收起' : `显示全部 ${theme.participants.length} 名参与者`}
            </Text>
            <Ionicons 
              name={participantsExpanded ? "chevron-up" : "chevron-down"} 
              size={16} 
              color="#3B82F6" 
            />
          </TouchableOpacity>
        )}
      </View>
    );
  };

  // 渲染上传模态框
  const renderUploadModal = () => {
    return (
      <Modal
        visible={uploadModalVisible}
        transparent
        animationType="slide"
        onRequestClose={() => {
          setUploadModalVisible(false);
          setShowUploadOptions(false); // 关闭模态框时也重置上传选项显示状态
        }}
      >
        <View className="flex-1 justify-end bg-black/50">
          <View className="bg-white rounded-t-3xl p-6">
            <View className="items-center mb-4">
              <View className="w-10 h-1 bg-gray-300 rounded-full mb-2" />
              <Text className="text-xl font-bold">添加收据</Text>
            </View>
            
            {uploading ? (
              <View className="items-center py-8">
                <ActivityIndicator size="large" color="#3B82F6" />
                <Text className="mt-4 text-gray-500">正在上传收据...</Text>
              </View>
            ) : (
              <View className="space-y-3">
                {!showUploadOptions ? (
                  // 主要选项
                  <>
                    <Pressable 
                      className="flex-row items-center p-4 bg-indigo-50 rounded-xl"
                      onPress={() => setShowUploadOptions(true)}
                    >
                      <View className="w-10 h-10 bg-indigo-100 rounded-full items-center justify-center">
                        <Ionicons name="sync-outline" size={24} color="#6366F1" />
                      </View>
                      <View className="ml-3">
                        <Text className="text-lg font-semibold">同步上传</Text>
                        <Text className="text-gray-500">单个文件拍照或选择上传</Text>
                      </View>
                    </Pressable>
                    
                    <Pressable 
                      className="flex-row items-center p-4 bg-amber-50 rounded-xl"
                      onPress={() => {
                        setUploadModalVisible(false);
                        setShowMultiUploadModal(true);
                      }}
                    >
                      <View className="w-10 h-10 bg-amber-100 rounded-full items-center justify-center">
                        <Ionicons name="documents-outline" size={24} color="#F59E0B" />
                      </View>
                      <View className="ml-3">
                        <Text className="text-lg font-semibold">批量上传</Text>
                        <Text className="text-gray-500">一次选择多个文件上传</Text>
                      </View>
                    </Pressable>
                  </>
                ) : (
                  // 同步上传的三个子选项
                  <>
                    <View className="flex-row items-center mb-3">
                      <Pressable 
                        onPress={() => setShowUploadOptions(false)}
                        className="p-2 mr-2"
                      >
                        <Ionicons name="arrow-back" size={24} color="#4B5563" />
                      </Pressable>
                      <Text className="text-lg font-semibold">选择上传方式</Text>
                    </View>
                  
                    <Pressable 
                      className="flex-row items-center p-4 bg-blue-50 rounded-xl"
                      onPress={pickDocument}
                    >
                      <View className="w-10 h-10 bg-blue-100 rounded-full items-center justify-center">
                        <Ionicons name="document-outline" size={24} color="#3B82F6" />
                      </View>
                      <View className="ml-3">
                        <Text className="text-lg font-semibold">从文件中选择</Text>
                        <Text className="text-gray-500">选择PDF或图片文件</Text>
                      </View>
                    </Pressable>

                    <Pressable 
                      className="flex-row items-center p-4 bg-green-50 rounded-xl"
                      onPress={pickImage}
                    >
                      <View className="w-10 h-10 bg-green-100 rounded-full items-center justify-center">
                        <Ionicons name="images-outline" size={24} color="#10B981" />
                      </View>
                      <View className="ml-3">
                        <Text className="text-lg font-semibold">从相册中选择</Text>
                        <Text className="text-gray-500">从手机相册选择图片</Text>
                      </View>
                    </Pressable>

                    <Pressable 
                      className="flex-row items-center p-4 bg-purple-50 rounded-xl"
                      onPress={takePhoto}
                    >
                      <View className="w-10 h-10 bg-purple-100 rounded-full items-center justify-center">
                        <Ionicons name="camera-outline" size={24} color="#8B5CF6" />
                      </View>
                      <View className="ml-3">
                        <Text className="text-lg font-semibold">拍照</Text>
                        <Text className="text-gray-500">使用相机拍摄发票照片</Text>
                      </View>
                    </Pressable>
                  </>
                )}
                
                <Pressable 
                  className="mt-3 p-4 items-center justify-center"
                  onPress={() => {
                    setUploadModalVisible(false);
                    setShowUploadOptions(false);
                  }}
                >
                  <Text className="text-gray-500">取消</Text>
                </Pressable>
              </View>
            )}
          </View>
        </View>
      </Modal>
    );
  };

  // 参与者搜索模态框
  const renderParticipantSearchModal = (isProxy = false) => {
    const modalVisible = isProxy ? showAddProxyModal : showAddParticipantModal;
    const setModalVisible = isProxy ? setShowAddProxyModal : setShowAddParticipantModal;
    const handleAdd = isProxy ? handleAddProxies : handleAddParticipants;
    
    return (
      <Modal
        visible={modalVisible}
        transparent
        animationType="slide"
        onRequestClose={() => setModalVisible(false)}
      >
        <View className="flex-1 justify-end bg-black/50">
          <View className="bg-white rounded-t-3xl p-6 h-3/4">
            <View className="items-center mb-4">
              <View className="w-10 h-1 bg-gray-300 rounded-full mb-2" />
              <Text className="text-xl font-bold">
                {isProxy ? '添加代理人' : '添加参与者'}
              </Text>
            </View>
            
            {/* 搜索框 */}
            <View className="mb-4">
              <View className="flex-row items-center border border-gray-300 rounded-lg px-3 py-2">
                <Ionicons name="search" size={20} color="#6B7280" />
                <TextInput
                  className="flex-1 ml-2"
                  placeholder="搜索用户..."
                  value={searchQuery}
                  onChangeText={handleSearchChange}
                />
              </View>
            </View>
            
            {/* 搜索结果 */}
            {isSearching ? (
              <ActivityIndicator size="small" color="#3B82F6" />
            ) : searchResults.length > 0 ? (
              <View className="mb-4 max-h-80">
                <Text className="text-sm text-gray-500 mb-2">搜索结果</Text>
                <FlatList
                  data={searchResults}
                  keyExtractor={(item) => item.userId}
                  renderItem={({ item }) => (
                    <TouchableOpacity 
                      className="flex-row items-center py-2 border-b border-gray-100"
                      onPress={() => handleSelectUser(item)}
                    >
                      <View className="w-8 h-8 rounded-full bg-blue-100 items-center justify-center mr-2">
                        <Text className="text-blue-600 font-bold">
                          {item.name.charAt(0).toUpperCase()}
                        </Text>
                      </View>
                      <View>
                        <Text className="font-medium">{item.name}</Text>
                        <Text className="text-sm text-gray-500">{item.email || item.userId}</Text>
                      </View>
                    </TouchableOpacity>
                  )}
                />
              </View>
            ) : searchQuery.length > 0 ? (
              <Text className="text-gray-500 mb-4">未找到匹配的用户</Text>
            ) : null}
            
            {/* 已选择用户 */}
            <View className="mb-4 flex-1">
              <Text className="text-sm text-gray-500 mb-2">已选择 ({selectedUsers.length})</Text>
              <FlatList
                data={selectedUsers}
                keyExtractor={(item) => item.userId}
                renderItem={({ item }) => (
                  <View className="flex-row items-center justify-between py-2 border-b border-gray-100">
                    <View className="flex-row items-center">
                      <View className="w-8 h-8 rounded-full bg-blue-100 items-center justify-center mr-2">
                        <Text className="text-blue-600 font-bold">
                          {item.name.charAt(0).toUpperCase()}
                        </Text>
                      </View>
                      <View>
                        <Text className="font-medium">{item.name}</Text>
                        <Text className="text-sm text-gray-500">{item.email || item.userId}</Text>
                      </View>
                    </View>
                    <TouchableOpacity onPress={() => handleRemoveUser(item.userId)}>
                      <Ionicons name="close-circle" size={20} color="#EF4444" />
                    </TouchableOpacity>
                  </View>
                )}
              />
            </View>
            
            {/* 按钮区域 */}
            <View className="flex-row mt-4">
              <TouchableOpacity 
                className="flex-1 py-3 bg-gray-200 rounded-lg mr-2 items-center"
                onPress={() => {
                  setModalVisible(false);
                  setSelectedUsers([]);
                  setSearchQuery('');
                  setSearchResults([]);
                }}
              >
                <Text className="font-medium text-gray-700">取消</Text>
              </TouchableOpacity>
              <TouchableOpacity 
                className="flex-1 py-3 bg-blue-500 rounded-lg items-center"
                onPress={handleAdd}
                disabled={selectedUsers.length === 0}
              >
                <Text className="font-medium text-white">添加</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    );
  };

  // 删除参与者确认对话框
  const renderDeleteParticipantConfirm = () => {
    const participant = theme?.participants.find(p => p.userId === participantToDelete);
    
    return (
      <Modal
        visible={showParticipantDeleteConfirm}
        transparent
        animationType="fade"
        onRequestClose={() => setShowParticipantDeleteConfirm(false)}
      >
        <View className="flex-1 justify-center items-center bg-black/50">
          <View className="bg-white rounded-lg p-6 w-5/6 max-w-md">
            <Text className="text-lg font-bold mb-4">确认移除参与者</Text>
            {participant && (
              <Text className="mb-4">
                确定要移除 {participant.name} 吗？此操作无法撤销。
              </Text>
            )}
            <View className="flex-row justify-end">
              <TouchableOpacity 
                className="py-2 px-4 rounded-lg mr-2"
                onPress={() => {
                  setShowParticipantDeleteConfirm(false);
                  setParticipantToDelete(null);
                }}
              >
                <Text className="text-gray-700">取消</Text>
              </TouchableOpacity>
              <TouchableOpacity 
                className="bg-red-500 py-2 px-4 rounded-lg"
                onPress={handleDeleteParticipant}
              >
                <Text className="text-white">删除</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    );
  };

  // 删除收据确认框
  const renderDeleteReceiptConfirm = () => {
    return (
      <Modal
        visible={showDeleteReceiptConfirm}
        transparent
        animationType="fade"
        onRequestClose={() => setShowDeleteReceiptConfirm(false)}
      >
        <View className="flex-1 justify-center items-center bg-black/50">
          <View className="bg-white rounded-lg p-6 w-5/6 max-w-md">
            <Text className="text-lg font-bold mb-4">确认删除收据</Text>
            <Text className="mb-4">
              确定要删除这张收据吗？此操作无法撤销。
            </Text>
            <View className="flex-row justify-end">
              <TouchableOpacity 
                className="py-2 px-4 rounded-lg mr-2"
                onPress={() => {
                  setShowDeleteReceiptConfirm(false);
                  setReceiptToDelete(null);
                }}
              >
                <Text className="text-gray-700">取消</Text>
              </TouchableOpacity>
              <TouchableOpacity 
                className="bg-red-500 py-2 px-4 rounded-lg"
                onPress={deleteReceipt}
              >
                <Text className="text-white">删除</Text>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>
    );
  };

  // 处理批量上传发票
  const handleBatchUpload = async (receipts: any[]) => {
    if (!theme || receipts.length === 0) return;
    console.log("上传发票:",receipts)
    const token = await getToken();
    setUploading(true);
    // 调用批量处理API
     const response = await fetch(`${API_BASE_URL}/api/themes/receipts/batch-upload`, {
       method: 'POST',
       headers: {
         'Authorization': `Bearer ${token}`,
         'Content-Type': 'application/json',
       },
       body: JSON.stringify({
         themeSerialNo: theme.serialNo,
         files: receipts
       }),
     });
     setUploading(false);
     
     if (response.ok) {
       // 重新加载主题数据以更新发票列表
       await loadThemeDetail();
       // 关闭批量上传模态框
       setShowMultiUploadModal(false);
     } else {
       Alert.alert('上传失败', '发票上传过程中出现错误');
     }
  };

  // 返回主要组件
  return (
    <>
      <Stack.Screen
        options={{
          title: theme?.title || '主题详情',
          headerTitleStyle: {
            fontWeight: 'bold',
          },
          headerRight: () => (
            <TouchableOpacity 
              className="pr-4"
              onPress={() => {
                Alert.alert('主题操作', '选择要执行的操作', [
                  { text: '取消', style: 'cancel' },
                  { text: '刷新', onPress: loadThemeDetail },
                  { text: '添加收据', onPress: () => setUploadModalVisible(true) },
                ]);
              }}
            >
              <Ionicons name="ellipsis-horizontal" size={24} color="#3B82F6" />
            </TouchableOpacity>
          )
        }}
      />
      <Container>
        {renderContent()}
        {renderUploadModal()}
        {renderParticipantSearchModal(false)}
        {renderParticipantSearchModal(true)}
        {renderDeleteParticipantConfirm()}
        {renderSignatureModal()}
        {renderHandwrittenSignatureModal()}
        {renderReceiptDetailModal()}
        {renderReceiptEditModal()}
        {renderDeleteReceiptConfirm()}
      </Container>
      {/* 批量上传模态框 */}
      <BatchReceiptUploader
        visible={showMultiUploadModal}
        onClose={() => setShowMultiUploadModal(false)}
        onBatchUploadComplete={handleBatchUpload}
        themeSerialNo={theme?.serialNo || ''}
      />
    </>
  );
}